package com.md.common.utils.wechat;

import com.md.common.exception.BaseBizException;
import com.md.common.utils.wechat.model.WxAccessToken;
import com.md.common.utils.wechat.model.WxJsApiTicket;
import com.md.common.utils.wechat.model.WxOauthAccessToken;
import com.md.common.utils.wechat.model.WxUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 功能描述：微信接口处理器
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-7-17 10:13
 * @since JDK 1.8
 */
@Component("wechatApiHandler")
public class WechatApiHandler {

    @Autowired
    private WechatMpApiProxy wechatMpApiProxy;
//    @Autowired
//    private RedisOperator redisOperator;

    public String getFwhAccessToken() throws BaseBizException {
        //从缓存获取，缓存不存在则调微信接口刷新access token
        synchronized (WxAccessToken.class){
            WxAccessToken wxAccessToken = null;
//            String wxAccessTokenStr = redisOperator.getString(RedisKeyConst.MP_FWH_ACCESS_TOKEN);
//            if(StringUtils.isNotEmpty(wxAccessTokenStr)){
//                wxAccessToken = JSONUtil.toBean(wxAccessTokenStr, WxAccessToken.class);
//            }
//            if(wxAccessToken == null){
//                wxAccessToken = wechatMpApiProxy.getFwhAccessToken();
//                redisOperator.setString(RedisKeyConst.MP_FWH_ACCESS_TOKEN, JSONUtil.toJSON(wxAccessToken), wxAccessToken.getExpires_in() - 300);
//            }
            return wxAccessToken.getAccess_token();
        }
    }

	public String getFwhJsApiTicket() throws BaseBizException {
		//从缓存获取，缓存不存在则调微信接口刷新jsapi_ticket
        synchronized (WxAccessToken.class){
            WxJsApiTicket wxJsApiTicket = null;
//            String wxJsApiTicketStr = redisOperator.getString(RedisKeyConst.MP_FWH_JSAPI_TICKET);
//            if(StringUtils.isNotEmpty(wxJsApiTicketStr)){
//                wxJsApiTicket = JSONUtil.toBean(wxJsApiTicketStr, WxJsApiTicket.class);
//            }
//            if(wxJsApiTicket == null){
//            	wxJsApiTicket = wechatMpApiProxy.getFwhJsApiTicket();
//                redisOperator.setString(RedisKeyConst.MP_FWH_JSAPI_TICKET, JSONUtil.toJSON(wxJsApiTicket), wxJsApiTicket.getExpires_in() - 300);
//
//            }
            return wxJsApiTicket.getTicket();
        }
	}

    public WxOauthAccessToken getOauthAccessToken(String code) throws BaseBizException {
        return wechatMpApiProxy.getOauthAccessToken(code);
    }

    public WxUserInfo getWxUserInfo(String oauthAccessToken, String openId) throws BaseBizException {
        return wechatMpApiProxy.getWxUserInfo(oauthAccessToken, openId);
    }


}
